<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\AppletCoupon;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
use function PHPUnit\Framework\exactly;

class DyCouponJob extends Job
{

    public $playet_id;

    public $applet_id;
    protected LoggerInterface $logger;



    public function __construct(string $handleFunciton,int $applet_coupon_id)
    {
        $container = ApplicationContext::getContainer();
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'dycoupon');
        $this->handleFunciton  = $handleFunciton;
        $this->appletCouponId = $applet_coupon_id;
    }

    public function handle()
    {
        try {
            $this->logger->info('开始处理抖音券的逻辑');
            $this->logger->info('执行的function 为',[$this->handleFunciton]);
            //查询couponId 是否存在，存在执行逻辑
            $appletCouponId =  $this->appletCouponId;
            $handleFunciton  = $this->handleFunciton;
            $appletCouponInfo = AppletCoupon::query()->where(['applet_coupon.id' => $appletCouponId])
                ->select(['applet_coupon.*','applet.app_id'])
                ->leftJoin('applet','applet.id','=','applet_coupon.applet_id')->first();
            $this->logger->info('判断小程序券是否存在 为',[$this->handleFunciton]);
            if(!empty($appletCouponInfo)){
                $accessToken = env('DY_TEST_TOKEN');
                $this->$handleFunciton($appletCouponInfo,$accessToken);
            }else{
                $this->logger->error('小程序优惠券不存在|错误：',[$appletCouponId]);

            }


        }catch (\Exception $e){

            $this->logger->error('请求处理抖音券的逻辑|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
    }

    public function create($appletCouponInfo,$accessToken){
        $this->logger->info('创建抖音小程序券',[$appletCouponInfo->id]);
        $this->createCoupon($appletCouponInfo,$accessToken);
    }

    public function createCoupon($appletCouponInfo,$accessToken){

        //查询所有小程序授权
//        $appletInfo =Applet::query()->where(['type' => 2])->pluck('app_id')->toArray();
        $params         = [
            "app_id"   =>$appletCouponInfo->app_id,
            "merchant_meta_no"   => (string)$appletCouponInfo->id,
            "name"   => $appletCouponInfo->name,
            "discount_type"   => $appletCouponInfo->discount_type,
            "receive_begin_time"   => strtotime($appletCouponInfo->receive_begin_time),
            "receive_end_time"   => strtotime($appletCouponInfo->receive_end_time),
            "valid_type"   => $appletCouponInfo->valid_type,
            "valid_begin_time"   => strtotime($appletCouponInfo->receive_begin_time),
            "valid_end_time"   => strtotime($appletCouponInfo->receive_end_time)+86400,
            "consume_path"   =>'pages/tabBar/square/square',
            "send_scene"    => 2,
            "stock_number"   => $appletCouponInfo->stock_number,
            "consume_desc"   => $appletCouponInfo->consume_desc,
        ];
        $url = self::$createUrl;
        $this->logger->info('请求创建小程序券数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求创建小程序券Url：'.$url);
        $postResult  = $this->request($params, $url,'POST',$accessToken);
        if($postResult['err_no'] == 0){
            $this->logger->info('调用创建小程序券接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            return $postResult['data'];
        }else{
            $this->logger->error('调用创建小程序券接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }


    public function dramaImageUpload($accessToken,$cover_url,$app_id){
        $params = [
            'resource_type' => 2,
            'ma_app_id' =>  $app_id,
            'image_meta' =>[
                'url' =>$cover_url,
            ]
        ];
        $uploadUrl = self::$uploadImageUrl;
        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$uploadUrl);
        //开始上传
        $uploadResult  = $this->request($params, $uploadUrl,'POST',$accessToken);
        if($uploadResult['err_no'] == 0){
            $this->logger->info('上传图片成功 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
            $open_pic_id = $uploadResult['data']['image_result']['open_pic_id'];
            return $open_pic_id;
        }else{
            $this->logger->error('上传图片失败 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
        }
        return false;
    }

    public function dramaCreate($accessToken,$playlet_name,$playlet_introduction,$seq_num,$open_pic_id,$tag_list,$registration_number,$app_id){
        $params = [
            'ma_app_id' =>  $app_id,
            'album_info' =>[
                'title' => $playlet_name,
                'seq_num' => $seq_num,
                'cover_list' =>[$open_pic_id],
                'year' => date('Y'),
                'album_status' => 3,
                'recommendation' => $playlet_name,
                'desp' =>$playlet_introduction,
                'qualification' => 2,
                'record_info' =>[
                    'ordinary_record_num' => $registration_number
                ],
                'tag_list' => $tag_list,
            ]
        ];
        $createUrl = self::$dramaCreateUrl;
        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$createUrl);
        //开始上传
        $createResult  = $this->request($params, $createUrl,'POST',$accessToken);
        if($createResult['err_no'] == 0){
            $this->logger->info('创建短剧成功 返回数据：'.PHP_EOL.var_export(['result' => $createResult], true));
            $album_id = $createResult['data']['album_id'];
            return $album_id;
        }else{
            $this->logger->error('创建短剧失败 返回数据：'.PHP_EOL.var_export(['result' => $createResult], true));
        }
        return false;
    }

    public function dydramaUpdate($accessToken,$album_id,$episode_info_list,$app_id){

        $params = [
            'ma_app_id' =>  $app_id,
            'album_id'=>$album_id,
            'episode_info_list' =>$episode_info_list
        ];
        $updateUrl = self::$dramaUpdateUrl;
//        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$updateUrl);
        //开始上传
        $updateResult  = $this->request($params, $updateUrl,'POST',$accessToken);
        if($updateResult['err_no'] == 0){
            $this->logger->info('编辑短剧成功 返回数据：'.PHP_EOL.var_export(['result' => $updateResult], true));
            return $updateResult['data'];
        }else{
            $this->logger->error('编辑短剧失败 返回数据：'.PHP_EOL.var_export(['result' => $updateResult], true));
        }
        return false;
    }



    public function dramaUpdate($accessToken,$album_id,$episode_info_list,$app_id){
        //一次只能上传100
        $returnData = [];
        if(count($episode_info_list) > 100){
            $divisionList  = [];
            $count = count($episode_info_list);
            foreach ($episode_info_list as $key => $item){
                $divisionList[] = $item;
                if(count($divisionList) == 100){
                    $updateData = $this->dydramaUpdate($accessToken,$album_id,$divisionList,$app_id);
                    $divisionList = [];
                    $returnData = $updateData;
                    sleep(10);
                }
                if($key+1 == $count){
                    $updateData = $this->dydramaUpdate($accessToken,$album_id,$divisionList,$app_id);
                    $returnData = $updateData;
                }



            }
        }else{
            $returnData = $this->dydramaUpdate($accessToken,$album_id,$episode_info_list,$app_id);
        }
        return $returnData;
    }
    public function dramaBind($accessToken,$album_id,$episode_id,$playlet_id,$playlet_epoisode_id,$appletInfo){
        try {
            sleep(1);

            foreach ($appletInfo as $applet){


                $params = [
                    'schema_bind_type' => 1,
                    'app_id' => $applet,
                    "single_schema_bind" => [
                        'album_id'=>$album_id,
                        "episode_id" => $episode_id,
                        "path" => "pages/videopage/videopage",
                        "params" => [
                            ["key" => "pid", "value" => (string)$playlet_id],
                            ["key" => "peid", "value" => (string)$playlet_epoisode_id],
                            ["key" => "dt", "value" => (string)time()] //无用的参数
                        ]
                    ]
                ];
                $updateUrl = self::$dramaBindUrl;
                $this->logger->info('请求小程序：',[$applet]);
//                $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
                $this->logger->info('请求Url：'.$updateUrl);
                //开始上传
                $reviewResult  = $this->request($params, $updateUrl,'POST',$accessToken);
                if($reviewResult['err_no'] == 0){
                    $this->logger->info('短剧绑定页面成功 短剧episode_id：',[$episode_id]);
//                    return $reviewResult;
                }else{
                    $this->logger->error('短剧绑定页面失败 返回数据：'.PHP_EOL.var_export(['result' => $reviewResult], true));
                }
            }
            return true;

        }catch (\Exception $e){
            $this->logger->error('请求抖音|错误：' . $e->getLine() . '|' . $e->getMessage());
            return $this->dramaBind($accessToken,$album_id,$episode_id,$playlet_id,$playlet_epoisode_id,$appletInfo);
        }
    }
    public function dramaReview($accessToken,$album_id,$app_id){
        $params = [
            'ma_app_id' =>  $app_id,
            'album_id'=>$album_id,
        ];
        $updateUrl = self::$dramaReviewUrl;
        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$updateUrl);
        //开始上传
        $reviewResult  = $this->request($params, $updateUrl,'POST',$accessToken);
        if($reviewResult['err_no'] == 0){
            $this->logger->info('短剧送审成功 返回数据：'.PHP_EOL.var_export(['result' => $reviewResult], true));
            return $reviewResult;
        }else{
            $this->logger->error('短剧送审失败 返回数据：'.PHP_EOL.var_export(['result' => $reviewResult], true));
        }
        return false;
    }


    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}